/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "can.h"
#include "dma.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "public.h"
#include "flash.h"

#include "power.h"
#include "bmi088.h"

#include "step.h"
#include "led.h"
#include "dyp.h"
#include "task.h"
#include "key.h"

#include <stdio.h>
#include <stdlib.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

int16_t sIcmTemp;

uint8_t aucGTRecvBuf[COMMON_MAX_LEN];

dev_t *pstDev = NULL;

extern uint16_t aucAdcBuf[40];

CAN_RxHeaderTypeDef RxHeader;
uint8_t RxData[8] = { 0 };

void canFilterConfig()
{

  CAN_FilterTypeDef sFilterConfig;

  sFilterConfig.FilterBank = 0;
  sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;
  sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;

  // sFilterConfig.FilterIdHigh = 0x200 << 5;
  // sFilterConfig.FilterIdLow = 0x0000;
  // sFilterConfig.FilterMaskIdHigh = 0x4F0 << 5;
  // sFilterConfig.FilterMaskIdLow = 0x0000;

  sFilterConfig.FilterIdHigh = 0x0000;
  sFilterConfig.FilterIdLow = 0x0000;
  sFilterConfig.FilterMaskIdHigh = 0x0000 ;
  sFilterConfig.FilterMaskIdLow = 0x0002;

  sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0;
  sFilterConfig.FilterActivation = ENABLE;
  sFilterConfig.SlaveStartFilterBank = 14;

  if (HAL_CAN_ConfigFilter(&hcan1, &sFilterConfig) != HAL_OK)
  {
    Error_Handler();
  }
}

void sendCanTest(uint32_t uiStID)
{
  CAN_TxHeaderTypeDef TxHeader;
  uint8_t TxData[8] = { 0 };
  uint32_t TxMailbox;

  TxHeader.StdId = uiStID;
  TxHeader.ExtId = 0;
  TxHeader.RTR = CAN_RTR_DATA;
  TxHeader.IDE = CAN_ID_STD;
  TxHeader.DLC = 8;
  TxHeader.TransmitGlobalTime = DISABLE;

  TxData[0] = 0;
  TxData[1] = 1;
  TxData[2] = 2;
  HAL_CAN_AddTxMessage(&hcan1, &TxHeader, TxData, &TxMailbox);
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  uint8_t regval = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC1_Init();
  MX_CAN1_Init();
  MX_TIM4_Init();
  MX_USART1_UART_Init();
  MX_TIM5_Init();
  MX_TIM2_Init();
  MX_TIM6_Init();
  MX_SPI3_Init();
  MX_USART6_UART_Init();
  /* USER CODE BEGIN 2 */


  canFilterConfig();

  printf("can stat = %d\r\n", HAL_CAN_Start(&hcan1));
  HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING);

  HAL_TIM_Base_Start(&htim2);
  HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);
  HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_2);
  HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_3);

  HAL_TIM_Base_Start_IT(&htim4);
  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2);
  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);

  HAL_TIM_Base_Start_IT(&htim5);
  HAL_TIM_Base_Start_IT(&htim6);

  HAL_ADC_Start_DMA(&hadc1, (uint32_t *)aucAdcBuf, 40);


  // HAL_ADC_Start_DMA(&hadc1, (uint32_t *)(pstDev->stDevFall.aucFallAdcBuf), 40);		

  // HAL_UART_Receive_DMA(&huart6, aucGTRecvBuf, COMMON_MAX_LEN);


  printf("begin\r\n");

  // POUT_24V_CT1_ON;
  // POUT_24V_CT2_ON;

  // POUT_12V_CT1_ON;
  // POUT_12V_CT2_ON;

  // POUT_5V_CT_ON;

  // PDEV_5V_ON;

 

  // BMI088_acc_cs(1);
  // BMI088_gry_cs(0);

  // SPI_Trans_rece(0 | 0x80);
  // SPI_Trans_rece(0xFF);
  // printf("gry id = %d\r\n",SPI_Trans_rece(0));

  // sendCanTest(0x200);
  // HAL_Delay(10);
  // sendCanTest(0x201);
  // HAL_Delay(10);
  // sendCanTest(0x209);
  // PCHARG_OFF;

  dev_init();
  pstDev->stDevFall.pucFallAdcBuf = aucAdcBuf;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {

    // if(HAL_GPIO_ReadPin(KEY_1_GPIO_Port,KEY_1_Pin) == 0)
    // {
    //   printf("key1 down\r\n");
    // }

    // if(HAL_GPIO_ReadPin(KEY_2_GPIO_Port,KEY_2_Pin) == 0)
    // {
    //   printf("key2 down\r\n");
    // }

    // if(HAL_GPIO_ReadPin(KEY_3_GPIO_Port,KEY_3_Pin) == 0)
    // {
    //   printf("key3 down\r\n");
    // }
    // HAL_GPIO_WritePin(DYP_OUT_1_GPIO_Port, DYP_OUT_1_Pin, 0);
    // HAL_GPIO_WritePin(DYP_OUT_2_GPIO_Port, DYP_OUT_2_Pin, 0);
    // HAL_GPIO_WritePin(DYP_OUT_3_GPIO_Port, DYP_OUT_3_Pin, 0);

    // HAL_Delay(10);

    // TIM2->CCR1 = 0;
    // TIM2->CCR2 = 0;
    // TIM2->CCR3 = 0;
    // TIM2->CNT = 0;
    // HAL_GPIO_WritePin(DYP_OUT_1_GPIO_Port, DYP_OUT_1_Pin, 1);
    // HAL_GPIO_WritePin(DYP_OUT_2_GPIO_Port, DYP_OUT_2_Pin, 1);
    // HAL_GPIO_WritePin(DYP_OUT_3_GPIO_Port, DYP_OUT_3_Pin, 1);
    // sendCanTest(CMD_RECV_LED);
    // HAL_Delay(500);



    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

    loop_task_run();

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 12;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) {
  if (HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &RxHeader, RxData) == HAL_OK)
  {
    canFramOperationCallback(&RxHeader, RxData);
  }
}



void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  // dypMonitCallback(GPIO_Pin);
  fastStopTrigCallback(GPIO_Pin);
}

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Instance == TIM2)
  {
    // printf("captu input\r\n");
    // if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
    // {
    //   if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == 0)
    //     printf("captu1 FALL cnt = %d\r\n", TIM2->CCR1);
    //   else
    //     printf("captu1 RSING cnt = %d\r\n", TIM2->CCR1);
    // }
    // if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
    // {
    //   if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_1) == 0)
    //     printf("captu2 FALL cnt = %d\r\n", TIM2->CCR2);
    //   else
    //     printf("captu2 RSING cnt = %d\r\n", TIM2->CCR2);
    // }
    // if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)
    // {
    //   if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_2) == 0)
    //     printf("captu3 FALL cnt = %d\r\n", TIM2->CCR3);
    //   else
    //     printf("captu3 RSING cnt = %d\r\n", TIM2->CCR3);
    // }

    if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
    {
      if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == 1)
        pstDev->stDevDyp1.uiMeasStartTime = TIM2->CCR1;
      else
        pstDev->stDevDyp1.iDistance = (int16_t)(((float)(TIM2->CCR1 - pstDev->stDevDyp1.uiMeasStartTime)) * 1.7f);
    }
    if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
    {
      if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_1) == 1)
        pstDev->stDevDyp2.uiMeasStartTime = TIM2->CCR2;
      else
        pstDev->stDevDyp2.iDistance = (int16_t)(((float)(TIM2->CCR2 - pstDev->stDevDyp2.uiMeasStartTime)) * 1.7f);
    }
    if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)
    {
      if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_2) == 1)
        pstDev->stDevDyp3.uiMeasStartTime = TIM2->CCR3;
      else
        pstDev->stDevDyp3.iDistance = (int16_t)(((float)(TIM2->CCR3 - pstDev->stDevDyp3.uiMeasStartTime)) * 1.7f);
    }

    // if(__HAL_TIM_GET_FLAG(&htim2, TIM_CHANNEL_1) != RESET)
    //   printf("captu1 cnt = %d\r\n", HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1));
    // if(__HAL_TIM_GET_FLAG(&htim2, TIM_CHANNEL_2) != RESET)
    //   printf("captu2\r\n");
    // if(__HAL_TIM_GET_FLAG(&htim2, TIM_CHANNEL_3) != RESET)
    //   printf("captu3\r\n");
  }
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Instance == TIM5)
  {
    dypTimeCallbak();
  }

  if (htim->Instance == TIM4)
  {
    ledTimeCallback();
    // printf("tim4 \r\n");
  }

  if (htim->Instance == TIM6)
  {
    pstDev->uiSysMsTime++;
  }

}

void HAL_UART_IDLE_Callback(UART_HandleTypeDef *huart)
{
  if (huart == &huart6)
  {
    if ((__HAL_UART_GET_FLAG(&huart6, UART_FLAG_IDLE) != 0))
    {
      __HAL_UART_CLEAR_IDLEFLAG(&huart6);
      HAL_UART_DMAStop(&huart6);
      uint8_t recv_len = COMMON_MAX_LEN - __HAL_DMA_GET_COUNTER(huart6.hdmarx);
      framCheck(aucGTRecvBuf, recv_len);
      HAL_UART_Receive_DMA(&huart6, aucGTRecvBuf, COMMON_MAX_LEN);

      // HAL_UART_Transmit(&huart6,aucGTRecvBuf,recv_len,0x55);
    }
  }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
